package core.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

@Slf4j
public class AddressUtil {
    private final static String key = "UGMBZ-CINWR-DDRW5-W52AK-D3ENK-ZEBRC";
    static final private String baseUrl = "https://apis.map.qq.com/jsapi?qt=geoc&addr=%s&key=" + key + "&output=jsonp&pf=jsapi&ref=jsapi&cb=qq.maps._svcb3.geocoder0";

    static public AddressEntity findByAddress(String address) {
        String url = String.format(baseUrl, address);
        HttpRequest request = HttpRequest.get(url);
        String response = request.execute().body();
        JSONObject entries = validJson(response.substring("qq.maps._svcb3.geocoder0".length() + 1, response.length() - 1));
        if (Objects.isNull(entries)){
            return null;
        }
        if (entries.getJSONObject("detail").containsKey("errmsg")){
            return null;
        }

        return new AddressEntity(
                entries.getJSONObject("detail").getDouble("pointx"),
                entries.getJSONObject("detail").getDouble("pointy")
        );
    }

    @Data
    @AllArgsConstructor
    static public class AddressEntity {
        double x; //经度
        double y; //纬度

    }


    private static JSONObject validJson(String response) {
        if (!JSONUtil.isTypeJSON(response)) {
            log.info("【响应非json】-》{}", response);
            return null;
        }
        return JSONUtil.parseObj(response);
    }
}
